<template>
  <div class="clearfix">
    <a-select
      v-model="theEntityId"
      :default-active-first-option="false"
      :disabled="disabled"
      :filter-option="false"
      :mode="mode"
      :placeholder="placeholder"
      :show-arrow="false"
      show-search
      @change="handleChange"
      @search="handleSearch">
      <a-select-option v-for="d in searchdata" :key="d.Id" :value="d.Id">
        {{ d.cCusName + '(' + d.cCusCode + ')' }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
export default {
  name: 'RemoteSearchByCondition',
  props: {
    entityId: { default: undefined, type: String }, // 绑定的客户ID
    mode: { default: 'default', type: String }, // 设置模式
    placeholder: { default: '', type: String }, // 提示文字
    disabled: { default: false, type: Boolean }, // 是否禁用
    isMyData: { default: false, type: Boolean }, // 是否查询私有数据
    api: { default: '', type: String } // API路径
  },
  model: {
    prop: 'entityId'
  },
  data () {
    return {
      entity: [],
      theEntityId: this.entityId,
      searchdata: []
    }
  },
  watch: {
    entityId (val) {
      if (val) {
        this.entityId = val
        this.custId = val
        this.BindingData()
      } else {
        this.custId = undefined
        this.searchdata = []
      }
    }
  },
  methods: {
    handleSearch (keyword) {
      if (keyword) {
        if (!keyword || keyword.length < 2) return this.$message.error('查询内容不能小于两个字')
        this.getSearch(keyword)
      } else {
        this.custId = undefined
        this.searchdata = []
      }
    },
    BindingData () {
      const id = this.custId
      if (id) {
        this.$http.post('/CustomerManagement/CustomerInfo/GetTheData', { id }).then(res => {
          if (res.Success) {
            if (res.Data) {
              this.searchdata = [res.Data]
            } else {
              this.searchdata = []
            }
          } else {
            this.$message.error(res.Msg)
          }
        })
      } else {
        this.searchdata = []
      }
    },
    getSearch (word) {
      if (!this.api && this.api == '') {
        return
      }
      this.$http
        .post(this.api, {
          PageIndex: 1,
          PageRows: 999,
          SortField: 'Id',
          SortType: 'desc',
          Search: { cCusName: word, cCusType: null }
        })
        .then(resJson => {
          if (resJson.Success) {
            this.searchdata = resJson.Data
          } else {
            this.$message.error(resJson.Msg)
            this.searchdata = []
          }
        })
    },
    handleChange (id) {
      this.BindingData()
      const obj = this.searchdata.find(val => {
        return val.Id === id
      })
      this.$emit('BindEntity', obj)
    }
  }
}
</script>
